<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-row>
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-button type="success" round size="large" @click="showAdd">新增</el-button>
            </el-form-item>
            <el-form-item>
              <el-input v-model="condition.name" placeholder="请输入姓名" @input="getAll(1)"/>
            </el-form-item>
            <el-form-item label="分类名称">
              <el-cascader
                  v-model="condition.categoryId"
                  :options="parentInfo"
                  :props="props"
                  clearable
                  :empty-values="[null, undefined]"
                  :value-on-clear="null"
                  @change="getAll(1)"
              />
            </el-form-item>
            <el-form-item label="是否上架">
              <el-select
                  v-model="condition.status"
                  clearable
                  placeholder="选择是否上架"
                  style="width: 150px"
                  :empty-values="[null, undefined]"
                  :value-on-clear="null"
                  @change="getAll(1)"
              >
                <el-option label="上架" :value="1"/>
                <el-option label="不上架" :value="0"/>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
    </template>
    <el-table :data="goodsInfo.list" style="width: 100%">
      <el-table-column prop="id" label="id" width="50px"/>
      <el-table-column label="分类图片">
        <template #default="scope">
          <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.urlList[0]"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.urlList"
              :preview-teleported="true"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称"/>
      <el-table-column prop="dscp" label="分类描述"/>
      <!--<el-table-column prop="detail" label="详情"/>-->
      <el-table-column prop="price" label="售价"/>
      <el-table-column prop="markPrice" label="标价"/>
      <el-table-column prop="purchasePrice" label="进价"/>
      <el-table-column prop="color" label="颜色"/>
      <el-table-column prop="version" label="版本"/>
      <el-table-column prop="count" label="数量"/>
      <el-table-column prop="category.name" label="所属分类"/>
      <el-table-column prop="score" label="评分"/>
      <el-table-column label="推荐">
        <template #default="scope">
          <el-tag v-if="scope.row.recom === 1" type="success">推荐</el-tag>
          <el-tag v-else type="info">不推荐</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否上架">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">上架</el-tag>
          <el-tag v-else type="info">不上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="showDetail(scope.row.id)">详情</el-button>
          <br/>
          <el-button size="small" @click="showUpdate(scope.row.id)">编辑</el-button>
          <br/>
          <el-popconfirm title="你确定要删除本商品吗？" confirm-button-text="确认" cancel-button-text="取消"
                         @confirm="delInfo(scope.row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-row class="row-bg" justify="space-evenly">
        <el-col :span="6">
          <el-pagination layout="prev, pager, next" :total="goodsInfo.total" :page-size="goodsInfo.pageSize"
                         @current-change="getAll"/>
        </el-col>
      </el-row>
    </template>
  </el-card>


  <!-- START 新增对话框 -->
  <el-dialog v-model="addVisible" title="新增商品" align-center style="width: 300px">
    <el-form :model="addInfoForm">
      <el-form-item label="名称" style="width: 250px">
        <el-input v-model="addInfoForm.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述" style="width: 250px">
        <el-input v-model="addInfoForm.dscp" autocomplete="off"/>
      </el-form-item>
      <!--<el-form-item label="详情" style="width: 250px">-->
      <!--  <el-input v-model="addInfoForm.detail" autocomplete="off"/>-->
      <!--</el-form-item>-->
      <el-form-item label="售价" style="width: 250px">
        <el-input v-model="addInfoForm.price" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="标价" style="width: 250px">
        <el-input v-model="addInfoForm.markPrice" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="进价" style="width: 250px">
        <el-input v-model="addInfoForm.purchasePrice" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="颜色" style="width: 250px">
        <el-input v-model="addInfoForm.color" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="版本" style="width: 250px">
        <el-input v-model="addInfoForm.version" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="数量" style="width: 250px">
        <el-input v-model="addInfoForm.count" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="所属分类">
        <el-cascader
            v-model="addInfoForm.categoryId"
            :options="parentInfo"
            :props="props"
            clearable
            :empty-values="[null, undefined]"
            :value-on-clear="null"
        />
      </el-form-item>
      <el-form-item label="是否推荐">
        <el-radio-group v-model="addInfoForm.recom">
          <el-radio :value="0" size="large">不推荐</el-radio>
          <el-radio :value="1" size="large">推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-radio-group v-model="addInfoForm.status">
          <el-radio :value="0" size="large">不上架</el-radio>
          <el-radio :value="1" size="large">上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="描述图片">
        <el-upload
            v-model:file-list="addInfoForm.picUrlList"
            action="#"
            list-type="picture-card"
            :http-request="handleUpload"
            :before-upload="addCategoryUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="图片预览"/>
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- END 新增对话框 -->


  <!-- START 修改对话框 -->
  <el-dialog v-model="updateVisible" title="更新商品" align-center style="width: 300px">
    <el-form :model="updateInfoForm">
      <el-form-item label="名称" style="width: 250px">
        <el-input v-model="updateInfoForm.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述" style="width: 250px">
        <el-input v-model="updateInfoForm.dscp" autocomplete="off"/>
      </el-form-item>
      <!--<el-form-item label="详情" style="width: 250px">-->
      <!--  <el-input v-model="updateInfoForm.detail" autocomplete="off"/>-->
      <!--</el-form-item>-->
      <el-form-item label="售价" style="width: 250px">
        <el-input v-model="updateInfoForm.price" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="标价" style="width: 250px">
        <el-input v-model="updateInfoForm.markPrice" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="进价" style="width: 250px">
        <el-input v-model="updateInfoForm.purchasePrice" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="颜色" style="width: 250px">
        <el-input v-model="updateInfoForm.color" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="版本" style="width: 250px">
        <el-input v-model="updateInfoForm.version" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="数量" style="width: 250px">
        <el-input v-model="updateInfoForm.count" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="所属分类">
        <el-cascader
            v-model="updateInfoForm.categoryId"
            :options="parentInfo"
            :props="props"
            clearable
            :empty-values="[null, undefined]"
            :value-on-clear="null"
        />
      </el-form-item>
      <el-form-item label="是否推荐">
        <el-radio-group v-model="updateInfoForm.recom">
          <el-radio :value="0" size="large">不推荐</el-radio>
          <el-radio :value="1" size="large">推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-radio-group v-model="updateInfoForm.status">
          <el-radio :value="0" size="large">不上架</el-radio>
          <el-radio :value="1" size="large">上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="描述图片">
        <el-upload
            v-model:file-list="updateInfoForm.picUrlList"
            action="#"
            list-type="picture-card"
            :http-request="handleUploadUpdate"
            :before-upload="addCategoryUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="updateRemove"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="图片预览"/>
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- END 修改对话框 -->

  <!-- START 详情修改-->
  <el-drawer v-model="drawer" direction="rtl">
    <template #header>
      <h4>修改商品详情</h4>
    </template>
    <template #default>
      <div v-if="drawer" style="border: 1px solid #ccc">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 500px; overflow-y: hidden;"
            v-model="updateInfoForm.detail"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
        />
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">提交</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- END 详情修改-->
</template>

<script setup>
// 全部信息
import '@wangeditor/editor/dist/css/style.css'
import {onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import categoryApi from "@/api/categoryApi.js";
import fileApi from "@/api/FileApi.js";
import {ElMessage} from "element-plus";
import goodsApi from "@/api/GoodsApi.js";

// 图片基本地址
const imagesBasePath = ref(import.meta.env.VITE_SERVER_ADDR)
// 分页信息
const goodsInfo = ref({
  list: [],
  total: 0,
  pageSize: 4,
  pageNum: 1,
})
// 搜索相关信息
const condition = ref({
  name: null,
  categoryId: null,
  status: null
})
// 连级查找相关配置
const props = ref({
  value: 'id',
  label: 'name',
  emitPath: false,
  children: 'childList'
})
// 父分类相关内容
const parentInfo = ref([])
// 新增弹出层
const addVisible = ref(false)
// 编辑弹出层
const updateVisible = ref(false)
// 详情抽屉
const drawer = ref(false)

// 新增信息
const addInfoForm = ref({
  name: '',
  dscp: '',
  detail: '',
  picList: [],
  picUrlList: [],
  price: '',
  markPrice: '',
  purchasePrice: '',
  color: '',
  version: '',
  count: '',
  recom: 1,
  categoryId: '',
  score: '',
  status: 1
})
// 修改信息
const updateInfoForm = ref({
  id: '',
  name: '',
  dscp: '',
  detail: '',
  picList: [],
  picUrlList: [],
  price: '',
  markPrice: '',
  purchasePrice: '',
  color: '',
  version: '',
  count: '',
  recom: 1,
  categoryId: '',
  score: '',
  status: 1
})

// ================================

// START 富文本所用材料========
const mode = ref('default')

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...' ,
  MENU_CONF:{
    uploadImage:{
      async customUpload(file, insertFn) {                   // JS 语法
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        let fd = new FormData();
        fd.append("file", file);
        let res = await fileApi.imagesUpload(fd)
        // let url = `${imagesBasePath.value}/file/images/${res.data}`
        let url = `/api/file/images/${res.data}`
        let alt = res.data
        // 最后插入图片
        insertFn(url, alt)
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// END 富文本所用材料========

// 获得全部的分类信息
const getAll = (pageNum) => {
  goodsApi.getByCondition(condition.value, pageNum, 4)
      .then(resp => {
        goodsInfo.value = resp.data
        goodsInfo.value.list.forEach(goods => {
          goods.urlList = []
          goods.picList.forEach(pic => {
            goods.urlList.push(imagesBasePath.value + '/file/images/' + pic.url)
          })
        })
        // console.log(goodsInfo.value)
      })
}
// 获取全部父分类信息
const getParentInfo = () => {
  categoryApi.getParentInfo(0)
      .then(resp => {
        parentInfo.value = resp.data;
      })
}

// 新增上传的请求
const handleUpload = (file) => {
  let fd = new FormData();
  fd.append("file", file.file);
  fileApi.imagesUpload(fd)
      .then(resp => {
        if (resp.code === 10000) {
          // console.log(file.file.uid);
          let uid = file.file.uid;
          addInfoForm.value.picList.push({uid: uid, url: resp.data})
        }
      });
}

// 更新上传的请求
const handleUploadUpdate = (file) => {
  let fd = new FormData();
  fd.append("file", file.file);
  fileApi.imagesUpload(fd)
      .then(resp => {
        if (resp.code === 10000) {
          // console.log(updateInfoForm.value.picUrlList[updateInfoForm.value.picUrlList.length - 1]);
          updateInfoForm.value.picUrlList[updateInfoForm.value.picUrlList.length - 1].realName = resp.data
        }
      });
}

// 新增之前的钩子函数
const addCategoryUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式要是JPG')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不要超过2MB!')
    return false
  }
  return true
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile.uid)
  let picList = addInfoForm.value.picList
  // console.log(picList)
  addInfoForm.value.picList = picList.filter(pic => pic.uid !== uploadFile.uid)
  // console.log(uploadFile, uploadFiles)
}
// 移除
const updateRemove = (uploadFile, uploadFiles) => {

}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 打开新增弹出层
const showAdd = () => {
  getParentInfo();
  addVisible.value = true;
}

// 打开更新弹出层
const showUpdate = (id) => {
  getParentInfo()
  goodsApi.getById(id)
      .then(resp => {
        if (resp.code === 10000) {
          updateInfoForm.value = resp.data

          updateInfoForm.value.picList.forEach(pic => {
            let url = imagesBasePath.value + '/file/images/' + pic.url
            if (updateInfoForm.value.picUrlList === undefined) {
              updateInfoForm.value.picUrlList = []
            }
            updateInfoForm.value.picUrlList.push({url: url, realName: pic.url})
          })
          updateVisible.value = true
        }
      })
}

// 显示详情
const showDetail = (id) => {
  goodsApi.getById(id)
      .then(resp => {
        if (resp.code === 10000) {
          updateInfoForm.value = resp.data

          updateInfoForm.value.picList.forEach(pic => {
            let url = imagesBasePath.value + '/file/images/' + pic.url
            if (updateInfoForm.value.picUrlList === undefined) {
              updateInfoForm.value.picUrlList = []
            }
            updateInfoForm.value.picUrlList.push({url: url, realName: pic.url})
          })
          drawer.value = true
        }
      })
}

// 提交新增
const submitAdd = () => {
  goodsApi.addInfo(addInfoForm.value)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getAll(goodsInfo.value.pageNum)
          getParentInfo()
          addVisible.value = false
          addInfoForm.value = {
            name: '',
            dscp: '',
            detail: '',
            picList: [],
            picUrlList: [],
            price: '',
            markPrice: '',
            purchasePrice: '',
            color: '',
            version: '',
            count: '',
            recom: 1,
            categoryId: '',
            score: '',
            status: 1
          }
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 提交更新
const submitUpdate = () => {
  updateInfoForm.value.picList = []
  updateInfoForm.value.picUrlList.forEach(pic => updateInfoForm.value.picList.push({url: pic.realName}))
  goodsApi.updateInfo(updateInfoForm.value)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getAll(goodsInfo.value.pageNum)
          getParentInfo()
          updateVisible.value = false
          drawer.value = false
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 删除商品
const delInfo = (id) => {
  goodsApi.delInfo(id)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getAll(goodsInfo.value.pageNum)
          getParentInfo()
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

getAll(1)
getParentInfo()
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>